package handler;

import service.*;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.*;
import java.sql.*;
import java.util.Objects;

public class EntityServlet extends HttpServlet {
    private static final long serialVersionUID = -4744661418439106106L;
    private EntityService service;

    @Override
    public void init() throws ServletException {
        super.init();
        service = new EntityServiceImpl();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter out = resp.getWriter();
        out.print("ok");
        out.flush();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/plain");
        String read = req.getParameter("read");
        String write = req.getParameter("write");
        PrintWriter out = resp.getWriter();
        try {
            if (Objects.nonNull(read) && read.length() > 0) {
                out.print(service.inquire(read));
            }
            if (Objects.nonNull(write) && write.length() > 0) {
                out.print(service.register(write));
            }
        } catch (SQLException | NamingException e) {
            e.printStackTrace();
        } finally {
            out.flush();
            out.close();
        }
    }
}
